package top.z.work.module.system.service.impl;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import top.z.work.framework.common.exception.ServiceException;
import top.z.work.module.system.cache.PermissionCache;
import top.z.work.module.system.entity.SystemRole;
import top.z.work.module.system.entity.SystemRoleRoute;
import top.z.work.module.system.entity.SystemRoute;
import top.z.work.module.system.entity.SystemUserRole;
import top.z.work.module.system.mapper.SystemRoleRouteMapper;
import top.z.work.module.system.mapper.SystemUserRoleMapper;
import top.z.work.module.system.service.PermissionService;
import top.z.work.module.system.service.SystemRoleService;
import top.z.work.module.system.service.SystemRouteService;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static top.z.work.module.system.constant.SystemErrorCode.USER_ID_NOT_EMPTY;

/**
 * 权限 Service 实现类
 */
@Slf4j
@Service
public class PermissionServiceImpl implements PermissionService {

    @Resource
    private SystemRouteService    menuService;
    @Resource
    private SystemRoleService     roleService;
    @Resource
    private PermissionCache       permissionCache;
    @Resource
    private SystemRoleRouteMapper systemRoleRouteMapper;
    @Resource
    private SystemUserRoleMapper  systemUserRoleMapper;

    /**
     * 查询指定用户的角色列表
     *
     * @param userId 用户ID
     * @return 角色列表
     */
    @Override
    public List<SystemRole> findUserRole(Long userId) {
        if (userId == null) {
            throw new ServiceException(USER_ID_NOT_EMPTY);
        }
        return systemUserRoleMapper.selectUserRoleList(userId);
    }

    /**
     * 查询指定用户的菜单列表
     *
     * @param userId 用户ID
     * @return 菜单列表
     */
    @Override
    public List<SystemRoute> findUserRoute(Long userId) {
        if (userId == null) {
            throw new ServiceException(USER_ID_NOT_EMPTY);
        }
        return systemRoleRouteMapper.selectUserMenuList(userId);
    }

    /**
     * 从缓存获取用户角色标识列表
     *
     * @param userId 用户ID
     * @return 用户角色标识列表
     */
    @Override
    public List<String> getUserRoleCodeListFromCache(Long userId) {
        List<String> roleCodeList = permissionCache.getUserRoleCode(userId);
        if (roleCodeList == null || roleCodeList.isEmpty()) {
            roleCodeList = this.findUserRole(userId)
                    .stream()
                    .map(SystemRole::getCode)
                    .collect(Collectors.toList());
            permissionCache.setUserRoleCode(userId, roleCodeList);
        }
        return roleCodeList;
    }

    /**
     * 从缓存获取用户权限标识列表
     *
     * @param userId 用户ID
     * @return 用户权限标识列表
     */
    @Override
    public List<String> getUserPermissionListFromCache(Long userId) {
        List<String> permissionList = permissionCache.getUserPermission(userId);
        if (permissionList == null || permissionList.isEmpty()) {
            permissionList = this.findUserRoute(userId)
                    .stream()
                    .map(SystemRoute::getAuthority)
                    .collect(Collectors.toList());
            permissionCache.setUserPermission(userId, permissionList);
        }
        return permissionList;
    }

    @Override
    public void assignUserRole(Long userId, Set<Long> roleId) {
        // 删除用户原有的数据
        systemUserRoleMapper.delete(new SystemUserRole().setUserId(userId));
        // 清理缓存
        permissionCache.removeUserRoleCode();
        permissionCache.removeUserPermission();
        // 添加角色
        List<SystemUserRole> userRoleList = roleId.stream()
                .map(id -> new SystemUserRole().setUserId(userId).setRoleId(id))
                .collect(Collectors.toSet())
                .stream()
                .toList();
        systemUserRoleMapper.insertBatch(userRoleList);
    }

    @Override
    public void assignRoleMenu(Long roleId, Set<Long> menuId) {
        // 删除原来的数据
        systemRoleRouteMapper.delete(new SystemRoleRoute().setRoleId(roleId));
        // 清理缓存
        permissionCache.removeUserRoleCode();
        permissionCache.removeUserPermission();
        // 添加菜单列表
        List<SystemRoleRoute> roleMenuList = menuId.stream()
                .map(id -> new SystemRoleRoute().setRoleId(roleId).setRouteId(id))
                .collect(Collectors.toSet())
                .stream()
                .toList();
        systemRoleRouteMapper.insertBatch(roleMenuList);
    }

    @Override
    public void processDeleteRole(Long roleId) {
        systemUserRoleMapper.delete(new SystemUserRole().setRoleId(roleId));
        systemRoleRouteMapper.delete(new SystemRoleRoute().setRoleId(roleId));
        // 删除缓存
        permissionCache.removeUserRoleCode();
        permissionCache.removeUserPermission();
    }

    @Override
    public void processDeleteMenu(Long menuId) {
        systemRoleRouteMapper.delete(new SystemRoleRoute().setRouteId(menuId));
        // 删除缓存
        permissionCache.removeUserRoleCode();
        permissionCache.removeUserPermission();
    }

    @Override
    public void processDeleteUser(Long userId) {
        // 删除用户角色
        systemUserRoleMapper.deleteById(userId);
        // 删除缓存
        permissionCache.removeUserPermission(userId);
        permissionCache.removeUserRoleCode(userId);
    }

}
